package com.stn.zjx.givingtreasure.activity.userprofile;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.FileUploadDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.FileNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.Base64FileUtils;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxPhotoTool;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class ModifyUserProfileActivity extends BaseActivity {

    private static final int PRC_PHOTO_PICKER = 1001;

    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.uuid)
    TextView uuid;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.user_sex)
    TextView userSex;
    @BindView(R.id.date_of_birth)
    TextView dateOfBirth;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.go_person_avatar)
    RelativeLayout goPersonAvatar;
    private Uri resultUri;
    BottomDialog uploadDialog;
    private BottomDialog sexDialog;
    private Dialog date_dilaog;
    MaterialCalendarView calendarView;
    TextView year,month;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.user_profile));
        uploadDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_select_images)
                .setCancelOutside(false)
                .setDimAmount(0.4f)
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.cancel)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();

                                    }
                                });
                        v.findViewById(R.id.location_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();
                                        choicePhoto(1);
                                    }
                                });
                        v.findViewById(R.id.camera_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();
                                        choicePhoto(0);
                                    }
                                });
                    }
                });


        sexDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_select_sex)
                .setCancelOutside(false)
                .setDimAmount(0.4f)
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.cancel)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sexDialog.dismiss();

                                    }
                                });
                        v.findViewById(R.id.male)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sexDialog.dismiss();
                                        updateSex(1);
                                    }
                                });
                        v.findViewById(R.id.female)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sexDialog.dismiss();
                                        updateSex(2);
                                    }
                                });
                        v.findViewById(R.id.unknown)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sexDialog.dismiss();
                                       updateSex(0);
                                    }
                                });
                    }
                });
        initDatePicker();
    }
   public void initDatePicker(){
       date_dilaog=new Dialog(this);
       date_dilaog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
       date_dilaog.setContentView(R.layout.dialog_date_picker);
       calendarView=date_dilaog.findViewById(R.id.calendarView);
       year=date_dilaog.findViewById(R.id.year);
       month=date_dilaog.findViewById(R.id.month);
       date_dilaog.findViewById(R.id.cancel_bt)
               .setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       date_dilaog.dismiss();
                   }
               });
       date_dilaog.findViewById(R.id.readby_bt)
               .setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       date_dilaog.dismiss();
                       Date my_date=calendarView.getSelectedDate().getDate();
                       updateDate(ToolsUtils.getYear(my_date),ToolsUtils.getMonth(my_date),ToolsUtils.getDay(my_date));
                   }
               });

       calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
           @Override
           public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay calendarDay, boolean selected) {
               year.setText(ToolsUtils.getYear(calendarDay.getDate()));
               month.setText(ToolsUtils.getMonth(calendarDay.getDate())+getString(R.string.month)+ToolsUtils.getDay(calendarDay.getDate())+getString(R.string.day)+" "+ToolsUtils.getWeek(calendarDay.getDate()));
           }
       });

   }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_modfiy_profile);
        ButterKnife.bind(this);
        initComponent();

    }


    @Override
    protected void onStart() {
        super.onStart();
        initUser();
    }
    public void initUser() {
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
            finish();
            return;
        }
        initLocationUser();
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        UserNetImpl.user_getuserprofile_bytoken(userOnline.getToken(), userOnline.getUserId() + "user_getuserprofile_bytoken",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful()&&!isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful()&&!isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }
                });
    }

    //用户在服务器手机号，密码校验正确
    private void loginSuccess(UserProfileDomain domain) {
        boolean isLogin = UserService.getInstance(this)
                .login(domain.getData());
        if (!isLogin) {
            boolean isExitLogin = UserService.getInstance(this)
                    .exitLogin();
            if (isExitLogin) {
                finish();
            }
        }
    }


    //设置用户资料
    public void user_getuserprofile_bytoken(String result) {
        if (result == null) {
            return;
        }
        Gson gson = new Gson();
        UserProfileDomain domain = gson.fromJson(result.trim(), UserProfileDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                loginSuccess(domain);
                initLocationUser();
                break;
            case BaseApi.REQUEST_LOGINEXIT_ERROR_CODE:

                break;
            case BaseApi.REQUEST_TOKEN_ERROR_CODE:

                break;
        }

    }

    @SuppressLint({"SetTextI18n", "SimpleDateFormat"})
    public void initLocationUser() {
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        Glide.with(this)
                .load(userOnline.getUserAvatar())
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        avatarCiv.setImageDrawable(resource);
                    }
                });
        userNickname.setText(userOnline.getUserNickname());
        switch (userOnline.getUserSex()) {
            case 0:
                userSex.setText(getText(R.string.unknown));
                break;
            case 1:
                userSex.setText(getText(R.string.male));
                break;
            case 2:
                userSex.setText(getText(R.string.female));
                break;
        }
        if (!userOnline.getUserYear().equals("")&&!userOnline.getUserMonth().equals("")&&!userOnline.getUserDay().equals("")) {
            dateOfBirth.setText(userOnline.getUserYear() + "-" + userOnline.getUserMonth() + "-" + userOnline.getUserDay());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date= null;
            try {
                date = (formatter.parse(userOnline.getUserYear() + "-" + userOnline.getUserMonth() + "-" + userOnline.getUserDay()));
            } catch (ParseException e) {
                e.printStackTrace();
                date=new Date();
            }
            year.setText(ToolsUtils.getYear(date));
            month.setText(ToolsUtils.getMonth(date)+getString(R.string.month)+ToolsUtils.getDay(date)+getString(R.string.day)+" "+ToolsUtils.getWeek(date));
            calendarView.setCurrentDate(date);
        } else {
            dateOfBirth.setText("");
            Date date=new Date();
            year.setText(ToolsUtils.getYear(date));
            month.setText(ToolsUtils.getMonth(date)+getString(R.string.month)+ToolsUtils.getDay(date)+getString(R.string.day)+" "+ToolsUtils.getWeek(date));
            calendarView.setCurrentDate(date);
        }
        if (TextUtils.isEmpty(userOnline.getUserSigntext())) {
            sign.setText(getString(R.string.sign_tip));
        } else {
            sign.setText(userOnline.getUserSigntext());
        }
        uuid.setText(String.valueOf(userOnline.getUserId()));


    }

    @OnClick({R.id.back_bt, R.id.go_person_avatar,R.id.go_user_nickname,
    R.id.go_sex,R.id.go_birthday,R.id.go_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.go_person_avatar:
                uploadDialog.show();
                break;
            case R.id.go_user_nickname:
                RxActivityTool.skipActivity(this,ModifyUserNicknameActivity.class);
                break;
            case R.id.go_sex:
                  sexDialog.show();
                break;
            case R.id.go_birthday:
                date_dilaog.show();
                break;
            case R.id.go_sign:
                RxActivityTool.skipActivity(this,ModifyUserSigntextActivity.class);
                break;
        }
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choicePhoto(int openType) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            switch (openType){
                case 0:
                    RxPhotoTool.openCameraImage(this);
                    break;
                case 1:
                    RxPhotoTool.openLocalImage(this);
                    break;
            }

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理

                    initUCrop(data.getData(),true);
                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                initUCrop(RxPhotoTool.imageUriFromCamera,true);
                break;
            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                resultUri = UCrop.getOutput(data);
              File file=new File(Objects.requireNonNull(RxPhotoTool.getImageAbsolutePath(this, resultUri)));
                uploadAvatar(file);

                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                assert cropError != null;
                showToast(cropError.getMessage());
                break;
        }
    }


    private void initUCrop(Uri uri,boolean isCircle) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".png"));
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.white));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.white));
        options.setToolbarWidgetColor(ActivityCompat.getColor(this,R.color.default_black));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
       options.setCircleDimmedLayer(isCircle);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }



    public void uploadAvatar(File file){

       String base=Base64FileUtils.encryptToBase64(file.getAbsolutePath());
        JSONObject data=new JSONObject();
        try {
            data.put("upfileBase64Content",base);
            data.put("upfileName",""+new Date().getTime());
            data.put("upfileSuffix","png");
            data.put("upfiletype","0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        FileNetImpl
                .upload_base64_file(data.toString(), "upload_base64_file", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                            showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                         dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful()&&!isFinishing()) {
                                  Gson gson=new Gson();
                                  FileUploadDomain   domain=gson.fromJson(response.body(), FileUploadDomain.class);
                                  switch (domain.getStatus()){
                                      case BaseApi.REQUEST_SUCCESS_CODE:
                                          if (UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser() == null) {
                                              return;
                                          }
                                          User userOnline = UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser();
                                          JSONObject data=new JSONObject();
                                          try {
                                              data.put("userAvatar",domain.getData().getPath());
                                          } catch (JSONException e) {
                                              e.printStackTrace();
                                          }
                                          UserNetImpl
                                                  .updateuserprofile_bytoken(data.toString(),userOnline.getToken(), "updateuserprofile_bytoken", new StringCallback() {
                                                      @Override
                                                      public void onFinish() {
                                                          super.onFinish();
                                                          dissmissLoading();
                                                      }

                                                      @Override
                                                      public void onStart(Request<String, ? extends Request> request) {
                                                          super.onStart(request);
                                                          showLoading();
                                                      }

                                                      @Override
                                                      public void onSuccess(Response<String> response) {
                                                          if(response.isSuccessful()){
                                                              StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                                                              switch (domain.getStatus()){
                                                                  case BaseApi.REQUEST_SUCCESS_CODE:
                                                   Glide.with(ModifyUserProfileActivity.this)
                                                           .load(file)
                                                           .apply(new RequestOptions().dontAnimate())
                                                           .into(new SimpleTarget<Drawable>() {
                                                               @Override
                                                               public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                                    avatarCiv.setImageDrawable(resource);
                                                               }
                                                           });
                                                       //              showToast(domain.getMessage());
                                                                      break;
                                                                  default:
                                                                      showToast(domain.getMessage());
                                                                      break;
                                                              }

                                                          }

                                                      }
                                                  });
                                          break;
                                       default:
                                           showToast(domain.getMessage());
                                           break;
                                  }

                              }
                    }
                });

    }



    public void updateSex(Integer sex){
        if (UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser() == null) {
            return;
        }
        User userOnline = UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser();
        JSONObject data=new JSONObject();
        try {
            data.put("userSex",sex);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserNetImpl
                .updateuserprofile_bytoken(data.toString(),userOnline.getToken(), "updateuserprofile_bytoken", new StringCallback() {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful()&&!isFinishing()) {
                            StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    switch (sex){
                                        case 0:
                                            userSex.setText(getString(R.string.unknown));
                                            break;
                                        case 1:
                                            userSex.setText(getString(R.string.male));
                                            break;
                                        case 2:
                                            userSex.setText(getString(R.string.female));
                                            break;
                                    }
                             //       showToast(domain.getMessage());
                                    break;
                                default:
                                    showToast(domain.getMessage());
                                    break;
                            }

                        }

                    }
                });
    }
    public void updateDate(String userYear,String userMonth,String userDay){

        if (UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser() == null) {
            return;
        }
        User userOnline = UserService.getInstance(ModifyUserProfileActivity.this).getOnlineLoginUser();
        JSONObject data=new JSONObject();
        try {
            data.put("userYear",userYear);
            data.put("userMonth",userMonth);
            data.put("userDay",userDay);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserNetImpl
                .updateuserprofile_bytoken(data.toString(),userOnline.getToken(), "updateuserprofile_bytoken", new StringCallback() {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful()&&!isFinishing()) {
                            StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    dateOfBirth.setText(userYear + "-" + userMonth + "-" + userDay);
                                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                                    Date date= null;
                                    try {
                                        date = (formatter.parse(userYear + "-" + userMonth+ "-" +userDay));
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                        date=new Date();
                                    }

                                    year.setText(ToolsUtils.getYear(date));
                                    month.setText(ToolsUtils.getMonth(date)+getString(R.string.month)+ToolsUtils.getDay(date)+getString(R.string.day)+" "+ToolsUtils.getWeek(date));
                                    calendarView.setCurrentDate(date);
                                 //   showToast(domain.getMessage());
                                    break;
                                default:
                                    showToast(domain.getMessage());
                                    break;
                            }

                        }

                    }
                });
    }

}
